<?php
namespace V1\Controller;


use V1\Logic\StockLogic;
use V1\Logic\MessageLogic;
use Think\Log;
class GameController extends BaseController {
    
     protected $errorCode = array(
        'recommend' => array(
            '-1'=>'用户token失效或有误',
            '-10'=>'更新状态失败',
        ) ,
        'index' => array(
            '-1'=>'用户token失效或有误',
            '-10'=>'数据不存在',
        ) ,
         'detail' => array(
            '-1'=>'用户token失效或有误',
            '-2'=>'参数异常',
            '-10'=>'更新状态失败',
            '-12'=>'该游戏已结束',
        ) ,
        'order' => array(
            '-1'=>'用户token失效或有误',
            '-2'=>'参数异常',
            '-10'=>'数据不存在',
            '-11'=>'该局游戏已结束',
            '-12'=>'股票因涨停或跌停，提前终止',
            '-13'=>'该局参与人数超过系统限制',
            '-14'=>'用户余额不足',
            '-15'=>'用户经验值不足已完成本次兑换，请充值后继续玩耍',
             '-16'=>'用户已参与本次游戏，无需再次提交',
            '1'=>'用户余额不足，是否使用经验值兑换并下注',
        ) 
        
    );
    protected  $gulGameTimes=[
                ['begin_time'=>25200,'end_time'=>46800],
                ['begin_time'=>32400,'end_time'=>36000],
                ['begin_time'=>36000,'end_time'=>39600],
                ['begin_time'=>45000,'end_time'=>48600],
                ['begin_time'=>48600,'end_time'=>52200],
        ];
    /**
     * 首页推荐
     * 当前这个交易日正在进行游戏列表
     * 如无 则返回空
     * 
    */
    public function recommend(){
       $data = array("code" => 0,"msg" => "","info"=>array());
       
       $user_token = I('user_token','');
       $isLogin =false;
       $uid=0;
       
       if(!empty($user_token)){
            $sessionModel = D('UserSession');
            $uid = $sessionModel->checkExpireTime($user_token);
            !empty($uid) && $isLogin=true;
       }
      
       $gameModel = M('Game');
       $where=array(
               'status'=>1,
               'trading_day'=>$this->day,
        );
        $games = $gameModel->where($where)->order('display_order desc,id desc')->cache(600)->limit(5)->select();
              
        $gameGulModel = D('GameDetail');
        $userStocklModel = M('UserStock');
        foreach ($games as $key => $value) {
             
            $gameInfo = $gameGulModel->getGamesInfoById($value['id']);
             
            $result = M('StockInfo')->where("stockcode='{$value['stock_code']}'")->field('stocklogo')->find();
            $value['stock_logo'] = !empty($result['stocklogo'])? str_replace('/Uploads','', $result['stocklogo']) :"";
             $games[$key] = array_merge($value, $gameInfo);
             if($isLogin){
                 $result = $userStocklModel->where(array('status'=>1,'user_id'=>$uid,'stock_code'=>$value['stock_code']))->find();
                  $games[$key]['isfollow']=!empty($result);
             }else{
               $games[$key]['isfollow']=false;  
             }
        }
        $data['info'] = $games;
        $this->responseResult($data);
    }
    /**
     * 游戏大厅
     * 当前这个交易日正在进行游戏列表
     */
    public function index(){
        $data = array("code" => 0,"msg" => "","info"=>array());
        $pageIndex = I('p',1,'intval');
        $pageSize = I('r',20,'intval');
        
        $fields=['id','stock_id','stock_code','stock_name'];
        
        $games = M('Game')->where(array('trading_day'=>$this->day,'status'=>1))->field($fields)->order('display_order desc,id desc')->page($pageIndex,$pageSize)->select();
        empty($games) && $this->responseError(-10);
        $gameGulModel = D('GameDetail');

        foreach ($games as $key => $value) {
             //计算实时的 当前股价 涨跌幅度 涨跌指数
             //涨跌预测（马蹄情绪） 热股排名（马蹄热度）
             //关注人数
             $gameBaseInfo = $gameGulModel->getGamesInfoById2($value['id']);
             $gameRealInfo = StockLogic::getStockInfo($this->day, $value['stock_code']);
             $gameInfo= array_merge($gameRealInfo,$gameBaseInfo);
             $games[$key]= array_merge($gameInfo,$value);
        }
        $data['info'] = $games;
        $this->responseResult($data);
    }
    /**
     * 游戏详情
     * 
     */
    public function detail(){
        
    $data = array("code" => 0,"msg" => "","info"=>array());
    $game_id = I('gameid',0);
    $stock_code = I('stockcode','');
    if(empty($game_id) || empty($stock_code)){
            return $this->responseError('-2',200);
    }
    
    $gameGulModel = D('GameDetail');
    $gameBaseInfo = $gameGulModel->getGamesInfoById2($game_id);
    $gameStockInfo = StockLogic::getStockInfo($this->day, $stock_code);
    $data['info']['stockInfo']=  array_merge($gameBaseInfo,$gameStockInfo);

    $closedGamesData = S($game_id.$stock_code.$this->day,'',array('prefix'=>'gameclosed'));
    
    if(empty($this->isOpen) && empty($closedGamesData) ){
        //显示上一个交易日 猜涨跌第四局 猜极值结果
        //--todo 获取上一个猜涨跌最后一局
        $lastGulIndex = $gameGulModel->getLastGulGame($game_id);
        
        $data['code']= -12;
        $data['msg']= $this->errorCode[strtolower(ACTION_NAME)]['-12'];
        
        if(!empty($lastGulIndex)){
            $data['info']['gulGameInfo']= $this->getGameInfo($game_id,$stock_code,$lastGulIndex, 0, false);
        }else{
            $data['info']['gulGameInfo']='未开启任何游戏';
        }
        
        $data['info']['extremunGameInfo']=  $this->getGameInfo($game_id,$stock_code,0, 0, false);
        
        S($game_id.$stock_code.$this->day,$data,array('expire'=>3600,'prefix'=>'gameclosed'));
        $this->responseResult($data);
        exit;
    }else if(!empty($closedGamesData)){
        $this->responseResult($closedGamesData);
        exit;
    }

     //游戏是否满足开局要求 有一种状态是临时修改状态 进入详情页的情况。
       //1.连续两个交易日涨停或跌停 不参与(这条规则在生成游戏信息时处理---todo)
       //2.新股次新股
       //3.当日停牌股票
       //4 其他人工干预
       //修改股票状态。。。
    $curDayTime= strtotime($this->day);
    $curTime = NOW_TIME-$curDayTime;//echo $curTime;
    $index=0;
    for ($index=1;$index < 5; $index++) {
            if($curTime>$this->gulGameTimes[$index]['begin_time'] && $curTime<=$this->gulGameTimes[$index]['end_time']){
                break;
            }
     }
    if($curTime>$this->gulGameTimes[2]['end_time'] && $curTime<$this->gulGameTimes[3]['begin_time']) $index=2;
    //echo 'index'.$index;
     
    
    
    //-----针对股票状态 在列表或推荐中考虑
    //$isNotJoin = StockLogic::manualInterveneNotJoinGame($day,$game_id);
    //-----针对股票游戏状态
    //9:30开盘及游戏进行过程中以后涨停或跌停 提前终止
    
    $isStop = StockLogic::isStop($game_id);
   
    $stopGamesData = S($game_id.$stock_code.$this->day,'',array('prefix'=>'gamestop'));
    
    if($isStop && empty($stopGamesData)){
        
        $data['code']= -12;
        $data['msg']= $this->errorCode[strtolower(ACTION_NAME)]['-12'];

        $data['info']['gulGameInfo']=  $this->getGameInfo($game_id,$stock_code, $index, 0, false);

        $data['info']['extremunGameInfo']=  $this->getGameInfo($game_id, $stock_code,0, 0, false);
        
        S($game_id.$stock_code.$this->day,$data,array('expire'=>7200,'prefix'=>'gamestop'));
        
        return $this->responseResult($data);
    
    }else if(!empty($stopGamesData)){
        return $this->responseResult($stopGamesData);
    }

   
     //---显示极值信息
    $symbol =  str_replace('-', '', $this->day).substr($stock_code, 2).'0';
    $curGameStatus = $gameGulModel->getGameStatus($game_id,$symbol);
    if($curTime>=$this->gulGameTimes[0]['begin_time'] && $curTime<=$this->gulGameTimes[0]['end_time']){
        //极值游戏
        //判断极值游戏是否开始，没开始则更新游戏状态为开始。
         //echo '极值游戏信息';
        $curGameStatus <> 1 && $gameGulModel->updateGameStatus($game_id,1,$symbol); 
        
        $data['info']['extremunGameInfo']=  $this->getGameInfo($game_id, $stock_code,0, 0, true);
        
       
    }else{
        //判断极值游戏是否结束，没结束则更新游戏状态为结束。
        $curGameStatus <> 2 && $gameGulModel->updateGameStatus($game_id,2,$symbol); 
       //显示极值游戏结果
        //13:00 - 15:00
        //15:00 - 16:00
        //16:00 - 23:59
        $data['info']['extremunGameInfo']=  $this->getGameInfo($game_id, $stock_code,0, 0, false);
    }
    
    //---显示猜涨跌信息
    if($curTime<$this->gulGameTimes[1]['begin_time']){
        //显示猜涨跌倒计时
        $data['info']['gulGameInfo']=  $this->getGameInfo($game_id,$stock_code,1, 0, false);
        $data['info']['gulGameInfo']['count_down']=32400-$curTime;
    }
    else if($curTime>$this->gulGameTimes[4]['end_time']){
       //显示第四局结果
        $data['info']['gulGameInfo']=  $this->getGameInfo($game_id,$stock_code,4, 0, false);
    }
    else if(($curTime>=$this->gulGameTimes[2]['end_time'] && $curTime<$this->gulGameTimes[3]['begin_time'])){
       //显示第二局结果 获取猜涨跌的信息
        $data['info']['gulGameInfo']=  $this->getGameInfo($game_id, $stock_code,2, 2, false);
    }
    else {
            //当日07:00-09:00 极值游戏开启 猜涨跌显示倒计时
            //当日09:00 猜涨跌第一局开始
            //当日10:00 猜涨跌第一局结束，第二局开始
            //当日11:00 猜涨跌第二局结束
            //当日12:30 猜涨跌第三局开始
            //当日13:30 猜涨跌第三局结束 第四局开始
            //当日13:00 极值游戏结束 显示结束信息
            //当日14:30 猜涨跌第四局结束 显示第四局信息
            //如果前一个游戏没有结束，则设置为结束
        if($index>1){//echo 'aaa '.$index;
            //$symbol = $this->day.$stock_code.($index-1);
            $symbol =  str_replace('-', '', $this->day).substr($stock_code, 2).($index-1);
            $preGameStatus = $gameGulModel->getGameStatus($game_id,$symbol);
            $preGameStatus <> 2 && $gameGulModel->updateGameStatus($game_id,2,$symbol); 
        }
        
        $symbol = str_replace('-', '', $this->day).substr($stock_code, 2).$index;

        //如果当前游戏没开始，则设置为开始。
        $curGameStatus = $gameGulModel->getGameStatus($game_id,$symbol);
        
        if(empty($curGameStatus)){
            $gameGulModel->updateGameStatus($game_id,1,$symbol);
        }
        //获取猜涨跌的信息
        $data['info']['gulGameInfo']=  $this->getGameInfo($game_id, $stock_code,$index, 4-$index, true);

    }
     $this->responseResult($data);
    }
    protected function getGameInfo($game_id,$stock_code,$index,$left_games=0,$continuous=true){
        $symbol =  str_replace('-', '', $this->day).substr($stock_code, 2).$index;
        //echo $symbol;
        $gameGulModel = D('GameDetail');
        $gulGameInfo = $gameGulModel->getGameInfoBySymbol($game_id,$symbol);
        $gulGameInfo['left_games']=$left_games;
        $gulGameInfo['continuous']=$continuous;
        if(!$continuous) unset($gulGameInfo['left_time']);
        return $gulGameInfo;

    }
    /**
     * 提交订单
     * 参数：
     * game_type:猜涨跌 猜极值
     * game_result:
     * 猜涨跌：涨或跌
     * 猜极值：极值数
     * 下注倍数：
     * 
     */
    public function order(){
      if(!IS_POST){
            throw new \Api\Library\Exception\BadRequest("该方法只支持POST请求", 1);
       }
        $data = array("code" => 0,"msg" => "","info"=>array());
       
        list($uid,$user_token) = $this->checkUserToken();
        
        $game_id = I('gameid',0);
        $stock_code = I('stockcode','');
        $bets = I('money',1,  'intval');//注数
        $multipe=I('multipe',1);//倍数
        $symbol=I('symbol','');
        $exchange=I('exchange',0);//是否支持兑换
        
//        $extreme_value=I('evalue',0);//
        $guess_result=I('result',0,'intval');//猜涨2或跌1 猜极值结果-10到10
        
        if(empty($stock_code) || empty($symbol)|| empty($guess_result) || ($bets*$multipe)>10){
             return $this->responseError('-2',200);
        }
        if(M('GameOrder')->where(array('symbol'=>$symbol,'user_id'=>$uid))->find()){
            return $this->responseError(-16,401,'重复提交');
        }
        
        //非正常原因结束
        $gameInfo =M('Game')->where('id='.$game_id)->cache(true,60)->find();
        if(empty($gameInfo['status'])){
            return $this->responseError(-12);
        }
        //正常原因结束--时间
        $game_index=  substr($symbol, strlen($symbol)-1);
        //echo $game_index;
        $curDayTime= strtotime($this->day);
        $curTime = NOW_TIME-$curDayTime;
       
        if($curTime>$this->gulGameTimes[$game_index]['end_time']){
            return $this->responseError(-11);
        }
        if($game_index==0 && $guess_result>10 || $guess_result<-10){
            return $this->responseError('-2',200);
        }
        //判断是否超过最大人数限制
        if($gameInfo['join_limit']>0){
            $join_count =M('UserGame')->where("game_id={$game_id} AND symbol='{$symbol}'")->count();
            if($gameInfo['join_limit']>=$join_count){
                return $this->responseError(-13);
            }
        }
        
        //用户是否满足下单条件
        $user_info = M('User')->where("id={$uid}")->field('money,experience')->find();
   
        //正常下单
        $need_money = $bets * $multipe;
        if($need_money>$user_info['money'] && empty($exchange)){
            
            
            
            $user_left_money = $user_info['experience']*C('GAME_EXPERIENCE_MONEY_EXCHANGE_RATIO')+$user_info['money'];
            
            if($user_left_money>=$need_money){
                
                $data['info']['exchange']=1;
                $data['code']=1;
                $data['msg'] =$this->errorCode[strtolower(ACTION_NAME)][1];
                return $this->responseResult($data);
                
            }else{
               return $this->responseError(-14);
            }
            
        }  else {
            //积分
            $exchange_types=['extremun','gul'];
	
            $exchange_type =$exchange_types[1];
            if(strcmp($game_index,'0')==0 ){
                $exchange_type =$exchange_types[0];
            }

            if(!empty($exchange) && $need_money>$user_info['money'] ){
               $need_experience=ceil(($need_money-$user_info['money'])*C('GAME_MONEY_EXPERIENCE_EXCHANGE_RATIO'));
               
               if($user_info['experience']<$need_experience){
                   return $this->responseError(-15);
               }
               $exchange_money = $need_experience*C('GAME_EXPERIENCE_MONEY_EXCHANGE_RATIO');
              
              //消费经验值兑换人民币以继续完成本次订单
              add_experience_log($uid, $need_experience, 1, $exchange_type, "{$gameInfo['stockname']}游戏兑换");
              exchange_money($uid, $exchange_money,"{$gameInfo['stockname']}游戏经验值兑换");
              
            }
                  
            $order_data=['game_id'=>$game_id,'symbol'=>$symbol,'user_id'=>$uid,
                'game_type'=>$exchange_type,'game_result'=>$guess_result,'remark'=>'',
                'extreme_value'=>0,'bets'=>$bets,'multipe'=>$multipe,'create_time'=>NOW_TIME,'status'=>1];
    
            //消费钱
            add_money_log($uid, $need_money, 1, $exchange_type, "{$gameInfo['stock_name']}游戏消费"); 
            //增加经验值
            add_experience_log($uid, 10, 0, $exchange_type, "{$gameInfo['stock_name']}游戏新增");
            //添加订单
            M('GameOrder')->add($order_data);
            
            //修改游戏总积分数 涨或跌积分 参与人数、涨或跌参与人数等..
            D('GameDetail')->addOrder($symbol,$exchange_type,$guess_result,$need_money);
            
            //新增用户游戏信息
            $user_game_data=['user_id'=>$uid,'game_id'=>$game_id,'symbol'=>$symbol,
                'money'=>$need_money,'win_money'=>0,'game_type'=>$exchange_type,
                'period'=> substr($symbol, 0,6),'create_time'=>NOW_TIME,'status'=>1,];
            
            M('UserGame')->add($user_game_data);

            //新增完成任务
            if(strcmp($game_index,'0')==0 ){
                add_task('join_extremun', $uid, 0, '首次参与涨跌幅奖励');
            }else{
                add_task('join_gul', $uid, 0, '首次参与猜涨跌奖励');
            }
             //新增通知
            $balance_time = M('GameDetail')->where(['game_id'=>$game_id,'symbol'=>$symbol])->cache(3600)->getField('balance_time');
            MessageLogic::finishedOrder($uid,$gameInfo['stock_name'],$exchange_type,$need_money,date('Y-m-d H:i',$balance_time));
            
            $data['msg'] = '成功下单';
            $data['info']['symbol']=$symbol;
            $data['info']['game_id']=$game_id;
            $data['info']['countinuous']=false;
            
            $this->responseResult($data);
        }
    }
    
  /*
    public function result(){
        
        Log::record("开始计算中奖结果",'INFO',true);
        if(empty($isOpen)){
             Log::record("当前日期是非交易日，无需计算",'INFO',true);
        }
        //当前待计算的局的结果
        
        $symbol='201506230000042' ;
        $game_id ='83';
        $game_type ='gul';//extremum
        
        $stock_price='';
        
         //根据股票价格算出输赢
        $game_result =2;//or false;最终结果输赢
        
        
        $where=['game_id'=>$game_id,'symbol'=>$symbol,'GameGul.status'=>0];
        $gameInfo=  D('GameGulView')->where($where)->find();
        var_dump($gameInfo);
        
        $distribute_scores=0;
        
        if($game_result==1){
            $distribute_scores=($gameInfo['down_scores']+$gameInfo['sys_pool'])*(1-$gameInfo['fee']);
        }else{
            $distribute_scores=($gameInfo['up_scores']+$gameInfo['sys_pool'])*(1-$gameInfo['fee']);
        }
        echo $distribute_scores.'<br/>';
        if(strcmp($game_type, 'extremum')==0){
            
            $extremum_values[] =5;//or false;最终结果极值
            
            if(abs($extremum_value[0])== 10){
                $extremum_values[] =$extremum_value[0]-1;
                $extremum_values[] =$extremum_value[0]-2;
            }else{
                $extremum_values[] =$extremum_value[0]-1;
                $extremum_values[] =$extremum_value[0]+1;
            }
            $distribute_scores1=$distribute_scores*0.65;
            $distribute_scores2=$distribute_scores*0.35;   
            
            $game_order_list =M('GameOrder')->where(['game_id'=>$game_id,'symbol'=>$symbol,
                                'game_result'=>$game_result,'remark'=>array('in',$extremum_values)])->select();
            
            if(isset($game_order_list) && count($game_order_list>0)){
                foreach ($game_order_list as $value) {

                    $prize_scores = round($value['bets']*$value['multipe']*(1+$distribute_ratio));
                    
                    
                    $user_coins = intval($user_scores/C('GAME_COIN_SCORE_EXCHANGE_RATIO'));
                    $user_scores = intval($user_scores% C('GAME_COIN_SCORE_EXCHANGE_RATIO'));

                    $user_coins>0 &&  add_coin_log($value['user_id'], $user_coins, 0, $game_type, "参与游戏{$game_id}猜涨跌局{$game_symbol}，获取元宝");
                    add_score_log($value['user_id'], $user_scores, 0, $game_type, "参与游戏{$game_id}猜涨跌局{$game_symbol}，获取元宝"); 
                }
            }
            
        }
        elseif (strcmp($game_type, 'gul')==0) {
            
            $game_order_list =M('GameOrder')->where(['game_id'=>$game_id,'symbol'=>$symbol,'game_result'=>$game_result])->select();
        
            $distribute_ratio = 0;
            
            if($game_result){
                $distribute_ratio=$distribute_scores/$gameInfo['up_scores'];
            }else{
                $distribute_ratio=$distribute_scores/$gameInfo['down_scores'];
            }
        
            foreach ($game_order_list as $value) {
                //给猜对的用户分配积分
                $prize_scores = round($value['bets']*$value['multipe']*(1+$distribute_ratio));
                $user_coins = intval($user_scores/C('GAME_COIN_SCORE_EXCHANGE_RATIO'));
                $user_scores = intval($user_scores% C('GAME_COIN_SCORE_EXCHANGE_RATIO'));
                
                $user_coins>0  && add_coin_log($value['user_id'], $user_coins, 0, $game_type, "用户参与游戏{$game_id}猜涨跌局{$game_symbol}，获取元宝");
                $user_scores>0 && add_score_log($value['user_id'], $user_scores, 0, $game_type, "用户参与游戏{$game_id}猜涨跌局{$game_symbol}，获取元宝"); 
                
               //
            }
        } 
    }*/
    /**
     * 获取用户奖金池
     * @param type $game_id
     * @param type $symbol
     * @param type $game_result
     * @return type
     */
    protected function get_user_pool_scores($game_id,$symbol,$game_result){
       
       $where=['game_id'=>$game_id,'symbol'=>$symbol,'game_result'=>$game_result];
       
       $total_bets =  M('GameOrder')->where($where)->sum('bets');
       $total_multipe =  M('GameOrder')->where($where)->sum('multipe');
       $user_pool =$total_bets*$total_multipe;
       
       return $user_pool;
    }
    
    /**
     * 校验奖池金额
     * @param type $origial_scores
     * @param type $game_id
     * @param type $symbol
     * @return type
     */
    protected function validate_distribute_scores($origial_scores,$game_id,$symbol,$game_result){
       
       $where=['game_id'=>$game_id,'symbol'=>$symbol,'game_result'=>$game_result];
       $total_bets =  M('GameOrder')->where($where)->sum('bets');
       $total_multipe =  M('GameOrder')->where($where)->sum('multipe');
       
       return ($total_multipe*$total_bets) == $origial_score;
    }
}